package cn.aifeix.consumer;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.order.domain.OrderCancelLog;
import cn.aifeix.order.domain.OrderPetAcquisition;
import cn.aifeix.order.service.IOrderCancelLogService;
import cn.aifeix.order.service.IOrderPetAcquisitionService;
import cn.aifeix.pet.domain.SearchMasterMsg;
import cn.aifeix.pet.service.ISearchMasterMsgService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @BelongsProject: rocketmq-test
 * @BelongsPackage: cn.itsource._01_hello
 * @Author: Director
 * @CreateTime: 2022-07-23  17:28
 * @Description: 消息消费者
 * @Version: 1.0
 */
@Component
@RocketMQMessageListener(consumerGroup = "pet_group_w", topic = "order-topic")
public class Consumer implements RocketMQListener {

    @Autowired
    private IOrderPetAcquisitionService orderPetAcquisitionService;

    @Autowired
    private ISearchMasterMsgService searchMasterMsgService;

    @Autowired
    private IOrderCancelLogService orderCancelLogService;

    @Override
    public void onMessage(Object message) {
//        System.out.println(message);
        Long id = Long.valueOf(String.valueOf(message));
        OrderPetAcquisition order = orderPetAcquisitionService.findById(id);
        if (null != order){
            // 查询寻主消息，修改寻主消息状态为1，清空shopId
            SearchMasterMsg searchMasterMsg = searchMasterMsgService.findById(order.getSearchMasterMsgId());
            if (searchMasterMsg == null){
                throw new BussinessException("寻主消息不存在！");
            }
            searchMasterMsg.setState(1);
            searchMasterMsg.setShopId(null);
            searchMasterMsgService.update(searchMasterMsg);
            if (0 == order.getState()){
                order.setState(-1);
                orderPetAcquisitionService.update(order);
                OrderCancelLog orderCancelLog = OrderCancelLog.builder()
                        .empId(order.getEmpId())
                        .msgId(order.getSearchMasterMsgId())
                        .orderSn(order.getOrderSn())
                        .cancelTime(new Date())
                        .shopId(order.getShopId())
                        .build();
                orderCancelLogService.add(orderCancelLog);
            }
        }

    }
}